Powershell Tutorial in 1 Day


What is PowerShell?

Windows PowerShell is object-oriented automation engine and scripting language. It is designed mainly for the system administrators. It helps IT, professionals, to control & automate the administration of the Window OS and other applications.

Features of Powershell

PowerShell Remoting: PowerShell allows scripts and cmdlets to be invoked on a remote machine. Background Jobs: It helps you to invoked script or pipeline asynchronously. You can run your jobs either on the local machine or multiple remotely operated machines. Transactions: Enable cmdlet and allows developers to perform Evening: This command helps you to listen, forwarding, and acting on management and system events. Network File Transfer: Powershell offers native support for prioritized, asynchronous, throttled, transfer of files between machines using the Background Intelligent Transfer Service (BITS) technology.

How to launch PowerShell

PowerShell is pre-installed in all latest versions of Windows. We need to launch PowerShell for that we need to follow the given steps: Step 1) Search for PowerShell in Windows. Select and Click Step 2) Power Shell Window Opens

PowerShell Cmdlet

A cmdlet which is also called Command let is a is a lightweight command used in the Window base PowerShell environment. PowerShell invokes these cmdlets in the command prompt. You can create and invoke cmdlets command using PowerShell APIS.

Cmdlet vs. Command:

Cmdlets are different from commands in other command-shell environments in the following manners − Cmdlets are .NET Framework class objects It can't be executed separately Cmdlets can construct from as few as a dozen lines of code Parsing, output formatting, and error presentation are not handled by cmdlets Cmdlets process works on objects. So text stream and objects can't be passed as output for pipelining Cmdlets are record-based as so it processes a single object at a time Most of the PowerShell functionality comes from Cmdlet's which is always in verb-noun format and not plural. Moreover, Cmdlet's return objects not text. A cmdlet is a series of commands, which is more than one line, stored in a text file with a .ps1 extension. A cmdlet always consists of a verb and a noun, separated with a hyphen. Some of the verbs use for you to learn PowerShell is: Get — To get something Start — To run something Out — To output something Stop — To stop something that is running Set — To define something New — To create something PowerShell commands Following is a list of important PowerShell Commands: Get-Help: Help about PowerShell commands and topics Example: Display help information about the command Format-Table Get-Help Format-Table Get-Command: Get information about anything that can be invoked Example: To generate a list of cmdlets, functions installed in your machine Get-Command Get-Service: Finds all cmdlets with the word 'service' in it. Example: Get all services that begin with "vm" Get-Service "vm*" Get- Member: Show what can be done with an object Example: Get members of the vm processes. Get-Service "vm*" | Get-Member Other Commands: Get Module Shows packages of commands Get Content This cmdlet can take a file and process its contents and do something with it Get- get Finds all cmdlets starting with the word 'get- Example: Create a Folder New-Item -Path 'X:\Guru99' -ItemType Directory Output

Powershell Data types:

Special Variables

Special Variable Description
$Error An array of error objects which display the most recent errors
$Host Display the name of the current hosting application
$Profile Stores entire path of a user profile for the default shell
$PID Stores the process identifier
$PSUICulture It holds the name of the current UI culture.
$NULL Contains empty or NULL value.
$False Contains FALSE value
$True Contains TRUE value

PowerShell Scripts

Powershell scripts are store in .ps1 file. By default, you can't run a script by just double-clicking a file. This protects your system from accidental harm. To execute a script: Step 1: right-click it and click "Run with PowerShell." Moreover, there is a policy which restricts script execution. You can see this policy by running the Get-ExecutionPolicy command. You will get one of the following output: Restricted— No scripts are allowed. This is the default setting, so it will display first time when you run the command. AllSigned— You can run scripts signed by a trusted developer. With the help of this setting, a script will ask for confirmation that you want to run it before executing. RemoteSigned— You can run your or scripts signed by a trusted developer. Unrestricted— You can run any script which you wants to run Steps to Change Execution Policy Step 1) Open an elevated PowerShell prompt. Right Click on PowerShell and "Run as Administrator" Step 2) Enter the Following commands Get-ExecutionPolicy Set-execution policy unrestricted Enter Y in the prompt Get-ExecutionPolicy

First PowerShell Script

In a notepad write the following command Write-Host "Hello, Guru99!" PowerShell Scripts have an extension ps1. Save the file as FirstScript.ps1 In Powershell, call the script using the command & "X:\FirstScript.ps1"

What is PowerShell ISE?

The Windows PowerShell Integrated Scripting Environment(ISE) is the default editor for Windows PowerShell. In this ISE, you can run commands, writer test, and debug scripts in an in a window base GUI environment. You can do multiline editing, syntax coloring, tab completion, selective execution and lots of other things. Windows PowerShell ISE also allows you to run commands in a console pane. However, it also supports panes that you can use to simultaneously view the source code of your script and other tools which you can plug into the ISE. You can even open up multiple script windows at the same time. This is specifically useful when you are debugging a script which uses functions defined in other scripts or modules. The same script we created in notepad, can be created in ISE Paste code into the editor Save Script Use F5 to run the script Observe output in the console Sample 2: The following code will give the Free Virtual Memory in your machine Get-WmiObject -Class Win32_OperatingSystem –ComputerName localhost | Select-Object -Property CSName,FreeVirtualMemory

PowerShell Concepts

Cmdlets Cmdlet are build-command written in .net languages like VB or C#. It allows developers to extend the set of cmdlets by loading and write PowerShell snap-ins.
FunctionsFunctions are commands which is written in the PowerShell language. It can be developed without using other IDE like Visual Studio and devs.
ScriptsScripts are text files on disk with a .ps1 extension
ApplicationsApplications are existing windows programs.
What ifTells the cmdlet not to execute, but to tell you what would happen if the cmdlet were to run.
ConfirmInstruct the cmdlet to prompt before executing the command.
VerboseGives a higher level of detail.
DebugInstructs the cmdlet to provide debugging information.
ErrorActionInstructs the cmdlet to perform a specific action when an error occurs. Allowed actions continue, stop, silently- continue and inquire.
ErrorVariableIt specifies the variable which holds error information.
OutVariableTells the cmdlet to use a specific variable to hold the output information
OutBufferInstructs the cmdlet to hold the specific number of objects before calling the next cmdlet in the pipeline.

Advantages of using PowerShell script

PowerShell scripts are really powerful and could do much stuff in fewer lines. Variables are declared in the form $<variable> Variables could be used to hold the output of command, objects, and values. "Type" of a variable need not be specified.

PowerShell Vs. Command Prompt

PowerShell Command Prompt
PowerShell deeply integrates with the Windows OS. It offers an interactive command line interface and scripting language. Command Prompt is a default command line interface which provided by Microsoft. It is a simple win32 application that can interact and talk with any win32 objects in the Windows operating system.
PowerShell uses what are known as cmdlets. It can be invoked either in the runtime environment or the automation scripts. No such features offer by command prompt.
PowerShell considers them as objects. So the output can be passed as an input to other cmdlets through the pipeline. Command Prompt or even the *nix shell, the output generated from a cmdlet is not just a stream of text but a collection of objects.
The PowerShell is very advanced regarding features, capabilities and inner functioning. Command prompt is very basic.

Applications of Powershell

Today, PowerShell has become an ideal choice for IT administrators as it eases management operation and effort in large corporate networks. For example, let's assume that you are managing a large network which contains more than four hundred servers. Now you want to implement a new security solution. This security solution depends on a certain service which needs to run on those servers. You can surely log in to each server and see if they have that service install and running or not. However, it certainly takes a lot of human errors as your staff needs to spend lots of time on this non-productive process. However, if you use PowerShell, then you could complete this task in just a few minutes. That's because the entire operation is done with a single script which gathers information about the services running on the servers. Summary Windows PowerShell is object-oriented automation engine and scripting language Powershell offers a well-integrated command-line experience for the operation system PowerShell first version 1.0 was released in 2006 PowerShell allows scripts and cmdlets to be invoked on a remote machine PowerShell is pre-installed in all latest versions of Windows A cmdlet is a lightweight command used in the Window base PowerShell environment Get, Start, Out, Stop, Set, New are important PowerShell commands Boolean, Byte, Chat, Decimal, Decimal, Long are important Data Type of PowerShell $Error. $Host, $Profile, $PID, $PSUICulture, $NULL are some special variable used in PowerShell The Windows PowerShell Integrated Scripting Environment(ISE) is the default editor for PowerShell PowerShell deeply integrates with the Windows OS whereas Command Prompt is a default command line interface which provided by Microsoft PowerShell has become an ideal choice for IT administrators as it eases management operation and effort in large corporate networks

How to Write and Run Scripts in the Windows PowerShell ISE

How to create and run scripts

You can open and edit Windows PowerShell files in the Script Pane. Specific file types of interest in Windows PowerShell are script files (.ps1), script data files (.psd1), and script module files (.psm1). These file types are syntax colored in the Script Pane editor. Other common file types you may open in the Script Pane are configuration files (.ps1xml), XML files, and text files. Note The Windows PowerShell execution policy determines whether you can run scripts and load Windows PowerShell profiles and configuration files. The default execution policy, Restricted, prevents all scripts from running, and prevents loading profiles. To change the execution policy to allow profiles to load and be used, see Set-ExecutionPolicy and about_Signing.

- To create a new script file

On the toolbar, click New, or on the File menu, click New. The created file appears in a new file tab under the current PowerShell tab. Remember that the PowerShell tabs are only visible when there are more than one. By default a file of type script (.ps1) is created, but it can be saved with a new name and extension. Multiple script files can be created in the same PowerShell tab.

- To open an existing script

On the toolbar, click Open, or on the File menu, click Open. In the Open dialog box, select the file you want to open. The opened file appears in a new tab.

- To close a script tab

Click the Close icon (X) of the file tab you want to close or select the File menu and click Close. If the file has been altered since it was last saved, you're prompted to save or discard it.

- To display the file path

On the file tab, point to the file name. The fully qualified path to the script file appears in a tooltip.

- To run a script

On the toolbar, click Run Script, or on the File menu, click Run.

- To run a portion of a script

In the Script Pane, select a portion of a script. On the File menu, click Run Selection, or on the toolbar, click Run Selection.

- To stop a running script

There are several ways to stop a running script. Click Stop Operation on the toolbar Press CTRL+BREAK Select the File menu and click Stop Operation. Pressing CTRL+C also works unless some text is currently selected, in which case CTRL+C maps to the copy function for the selected text.

How to write and edit text in the Script Pane

You can copy, cut, paste, find, and replace text in the Script Pane. You can also undo and redo the last action you just performed. The keyboard shortcuts for these actions are the same shortcuts used for all Windows applications.

- To enter text in the Script Pane

Move the cursor to the Script Pane by clicking anywhere in the Script Pane, or by clicking Go to Script Pane in the View menu. Create a script. Syntax coloring and tab completion provide a richer editing experience in Windows PowerShell ISE. See How to Use Tab Completion in the Script Pane and Console Pane for details about using the tab completion feature to help in typing.

- To find text in the Script Pane

To find text anywhere, press CTRL+F or, on the Edit menu, click Find in Script. To find text after the cursor, press F3 or, on the Edit menu, click Find Next in Script. To find text before the cursor, press SHIFT+F3 or, on the Edit menu, click Find Previous in Script.

- To find and replace text in the Script Pane

Press CTRL+H or, on the Edit menu, click Replace in Script. Enter the text you want to find and the replacement text, then press ENTER.

- To go to a particular line of text in the Script Pane

In the Script Pane, press CTRL+G or, on the Edit menu, click Go to Line. Enter a line number.

- To copy text in the Script Pane

In the Script Pane, select the text that you want to copy. Press CTRL+C or, on the toolbar, click the Copy icon, or on the Edit menu, click Copy.

- To cut text in the Script Pane

In the Script Pane, select the text that you want to cut. Press CTRL+X or, on the toolbar, click the Cut icon, or on the Edit menu, click Cut.

- To paste text into the Script Pane

Press CTRL+V or, on the toolbar, click the Paste icon, or on the Edit menu, click Paste.

- To undo an action in the Script Pane

Press CTRL+Z or, on the toolbar, click the Undo icon, or on the Edit menu, click Undo.

- To redo an action in the Script Pane

Press CTRL+Y or, on the toolbar, click the Redo icon, or on the Edit menu, click Redo.

How to save a script

An asterisk appears next to the script name to mark a file that hasn't been saved since it was changed. The asterisk disappears when the file is saved.

- To save a script

Press CTRL+S or, on the toolbar, click the Save icon, or on the File menu, click Save.

- To save and name a script

On the File menu, click Save As. The Save As dialog box will appear. In the File name box, enter a name for the file. In the Save as type box, select a file type. For example, in the Save as type box, select 'PowerShell Scripts (*.ps1)'. Click Save.

- To save a script in ASCII encoding

By default, Windows PowerShell ISE saves new script files (.ps1), script data files (.psd1), and script module files (.psm1) as Unicode (BigEndianUnicode) by default. To save a script in another encoding, such as ASCII (ANSI), use the Save or SaveAs methods on the $psISE.CurrentFile object. The following command saves a new script as MyScript.ps1 with ASCII encoding. $psISE.CurrentFile.SaveAs("MyScript.ps1", [System.Text.Encoding]::ASCII) The following command replaces the current script file with a file with the same name, but with ASCII encoding. $psISE.CurrentFile.Save([System.Text.Encoding]::ASCII) The following command gets the encoding of the current file. $psISE.CurrentFile.encoding Windows PowerShell ISE supports the following encoding options: ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, UTF8, and Default. The value of the Default option varies with the system. Windows PowerShell ISE doesn't change the encoding of script files when you use the Save or Save As commands.